package com.simou.filter;

import com.alibaba.fastjson.JSON;
import com.simou.common.BaseContext;
import com.simou.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.simou.common.R.error;


@Slf4j
@WebFilter(filterName = "LoginCheckFilter",urlPatterns = "/*")
// 过滤器检验登录
public class LoginCheckFilter implements Filter {
//    spring的路径匹配器，检查路径，主要是利用其支持通配符的特性
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 转换类型以使用 getRequestURI 方法
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        log.info("请求经过了过滤器，请求路径：{}",request.getRequestURI());

//        放行的url
        String[] urls = {
                "/",
                "/backend/**",
                "/front/**",
                "/employee/login",
                "/employee/logout",
                "/common/**",
                "/user/sendMsg",    //移动端发送短信
                "/user/login",      //移动端登录
        };

        boolean check = check(request.getRequestURI(), urls);

        // 1.若为放行url，则放行
        if(check){
//            log.info("本次请求无需处理 {}",request.getRequestURI());
            filterChain.doFilter(request,response);
            return;
        }

//        2.判断电脑端登录
        if(request.getSession().getAttribute("employee")!=null){
            BaseContext.setCurrentId((Long) request.getSession().getAttribute("employee"));
            log.info("employee已登录");
            filterChain.doFilter(request,response);
            return;
        }

        // 判断移动端登录
        if(request.getSession().getAttribute("user")!=null){
            log.info("用户已登录，id为{}",request.getSession().getAttribute("user"));

            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request,response);
            return;
        }

        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        log.info("拦截了请求:{}",request.getRequestURI());
    }

//    检查路径是否匹配
    public boolean check(String path,String[] urls){
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, path);
            if (match){
                return true;
            }
        }
        return false;
    }
}
